﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Model.ViewModels;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Controllers
{
    public class AgentController : BaseController
    {
        public IAgentContract AgentContract { get; set; }
        public IAgentCityContract AgentCityContract { get; set; }
        public IAreaContract AreaContract { get; set; }


        [Description("代理商-列表")]
        //[GlobalAuthorization]
        public ActionResult Index()
        {
            return View();
        }

        [Description("代理商-列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "")
        {
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());
            //login.DepId
            var query = from m in AgentContract.Entities.Where(x => !x.IsDeleted) select m;

            //if (login.Authority == 2)
            //{
            //    query = query.Where(x => x.DepId == login.DepId);
            //}

            //条件搜索
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Name.Contains(search));
            }

            //var list = (from m in query
            //            select new UserShow
            //            {
            //                Id = m.Id,
            //                Intermediary = (from m1 in IntermediaryContract.Entities where m1.Id == m.IntermediaryID select m1.Name).FirstOrDefault(),
            //                Name = m.Name,
            //                Phone = m.Phone,
            //                Declaration = m.Declaration,
            //                OperationPeriod = m.OperationPeriod,
            //                AccountBank = m.AccountBank,
            //                AccountUserName = m.AccountUserName,
            //                AccountNumber = m.AccountNumber,
            //                City = (from m2 in AreaContract.Entities where m2.Id == m.CityID select m2.Name).FirstOrDefault(),
            //                CreatedTime = m.CreatedTime
            //            });

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.CreatedTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<Agent>().AsQueryable();// null;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("代理商-添加")]
        //[GlobalAuthorization]
        public ActionResult Insert()
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            //initDepartAndPosition(null);
            return View();
        }

        [Description("代理商-添加")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult InsertAsync(Agent entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var query = AgentContract.CheckExists(m => m.Name.Equals(entity.Name) && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的代理商";
                }
                else
                {
                    //如果选择部门不为空--默认加入考勤设置-----赵兴昌
                    //if (entity.DepId != 0)
                    //{
                    //    var dep = DepContract.GetByKey(entity.DepId);
                    //    entity.AttSetId = dep.AttSetId;
                    //}
                    //if (entity.Authority == 2) entity.IsLiability = true;

                    //entity.CreateTime = DateTime.Now;
                    
                    var count = AgentContract.Insert(entity);
                    if (count > 0)
                    {                        
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                        
                        //if (entity.DepId != 0 && entity.IsLiability)
                        //{
                        //    var newuser = Contract.Entities.Where(d => d.UserName == entity.UserName).FirstOrDefault();
                        //    UpdateIsLiability(entity.DepId, newuser.Id);//更新部门其他人员的部门负责人状态
                        //    UpdateAuthority(entity.DepId, newuser.Id);
                        //}

                        //UserInfoModel uiModel = new UserInfoModel();
                        //uiModel.Birthday = DateTime.Parse("1980-01-01");
                        //uiModel.IDNumber = "";//身份证号码
                        //uiModel.Address = "";
                        //uiModel.EMail = "";
                        //uiModel.Education = 0;
                        //uiModel.Nation = 0;//民族
                        //uiModel.PhotoId = 1;
                        //uiModel.Sex = 2;
                        //uiModel.UserId = (from m in Contract.Entities where m.UserName == entity.UserName select m.Id).FirstOrDefault();

                        //UserInfoContract.Insert(uiModel);

                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }                    
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("代理商-修改")]
        //[GlobalAuthorization]
        public ActionResult Edit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = AgentContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null)
            {
                throw new Exception("未找到该实体");
            }
            
            //initDepartAndPosition(entity);
            ViewData["entity"] = entity;
            return View();
        }

        [Description("代理商-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditAsync(Agent entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var query = AgentContract.CheckExists(m => m.Name.Equals(entity.Name) && m.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的代理商";
                }
                else
                {
                    //如果选择部门不为空--默认加入考勤设置-----赵兴昌
                    //if (entity.DepId != 0)
                    //{
                    //    var dep = DepContract.GetByKey(entity.DepId);
                    //    entity.AttSetId = dep.AttSetId;
                    //}
                    //if (entity.Authority == 2) entity.IsLiability = true;

                    //获取原纪录
                    var temp = AgentContract.GetByKey(entity.Id);
                    //修改指定项
                    temp.Name = entity.Name;
                    temp.Remark = entity.Remark;
                    temp.ServicePhone = entity.ServicePhone;
                    
                    var count = AgentContract.Update(temp);
                    if (count > 0)
                    {
                        //if (entity.DepId != 0 && entity.IsLiability == true)
                        //{
                        //    UpdateIsLiability(entity.DepId, entity.Id);//更新部门其他人员的部门负责人状态
                        //    UpdateAuthority(entity.DepId, entity.Id);
                        //}

                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("代理商-查询")]
        [HttpPost, AjaxOnly]
        public ActionResult GetModelAsync(int id)
        {
            var result = new AjaxResult();

            try
            {
                var model = AgentContract.GetByKey(id);

                if (model != null)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                    result.Data = model;
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "获取失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }

        [Description("代理商-删除")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                AgentContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new Agent { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        //关联城市列表===================================================================================================================

        [Description("关联城市-列表")]
        //[GlobalAuthorization]
        public ActionResult CityIndex(int id)
        {
            ViewData["agentid"] = id;
            return View();
        }

        [Description("关联城市-列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult CityIndexAsync(int agentId, int pageIndex, int pageSize, string search = "")
        {
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());
            //login.DepId
            var query = from m in AgentCityContract.Entities.Where(x => x.AgentID.Equals(agentId)) select m;

            //if (login.Authority == 2)
            //{
            //    query = query.Where(x => x.DepId == login.DepId);
            //}

            

            var list = (from m in query
                        select new AgentCityShow
                        {
                            Id = m.Id,
                            Name = (from m2 in AreaContract.Entities where m2.Id == m.CityID select m2.Name).FirstOrDefault(),
                            EasyName = (from m3 in AreaContract.Entities where m3.Id == m.CityID select m3.EasyName).FirstOrDefault(),
                            ZoneDescription = (from m4 in AreaContract.Entities where m4.Id == m.CityID select m4.ZoneDescription).FirstOrDefault(),
                            State = m.State==0? "下线" : "上线"
                        });

            //条件搜索
            if (!string.IsNullOrWhiteSpace(search))
            {
                list = list.Where(m => m.Name.Contains(search));
            }

            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderBy(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<AgentCityShow>().AsQueryable();// null;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = list.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("关联城市-删除")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAgentCityAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                AgentCityContract.DeleteDirect(m => idsInt.Contains(m.Id));

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("关联城市-添加")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult InsertAgentCityAsync(int agentid, string cityid)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                AgentCity entity = new AgentCity();
                entity.AgentID = agentid;
                entity.CityID = cityid;
                entity.State = 1;

                var query = AgentCityContract.CheckExists(m => m.AgentID.Equals(entity.AgentID) && m.CityID.Equals(entity.CityID));
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的城市";
                }
                else
                {
                    var count = AgentCityContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        //区域城市列表===================================================================================================================

        [Description("城市-列表")]
        //[GlobalAuthorization]
        public ActionResult AreaIndex(int id)
        {
            ViewData["agentid"] = id;
            return View();
        }

        [Description("城市-列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult AreaIndexAsync()
        {
            var data = AreaContract.Entities.Where(m => m.ParentID == "0").Select(m => new
            {
                id = m.Id,
                text = m.Name,

                children = AreaContract.Entities.Where(n => n.ParentID == m.Id).Select(n => new
                {
                    id = n.Id,
                    text = n.Name,
                    children = AreaContract.Entities.Where(t => t.ParentID == n.Id).Select(t => new
                    {
                        id = t.Id,
                        text = t.Name
                    })
                })
            }).ToList();

            return JsonEx(new
            {
                id = "0",
                text = "全部",
                children = data
            });
        }
    }
}